import datetime

from application import db
from application.apps.case_library.service import case_library_service
from application.libs import const
from application.models.models import JobTask, Case, Taskcase, Node


# 查询未删除项目
def selecttaskall():
    result = db.session.query(JobTask).filter(JobTask.status != 3).all()
    db.session.commit()
    # db.session.close()
    list = []
    dic = {}
    for a in result:
        content = {
            'id': a.id,
            'task_name': a.task_name,
            'job_name': a.job_name,
            'status': a.status,
            'ding_token': a.ding_token,
            'create_time': a.create_time.strftime("%Y-%m-%d")
        }
        list.append(content)
    dic['items'] = list
    dic['total'] = len(list)
    return dic


def get_task_list(task_querys):
    parm = []
    if task_querys['create_time'].strip() != '':
        parm.append(Case.is_deploy == task_querys['create_time'])
    if task_querys['ding_token'].strip() != '':
        parm.append(Case.project_name == task_querys['ding_token'])
    if task_querys['id'].strip() != '':
        parm.append(Case.case_type == task_querys['id'])
    if task_querys['job_name'].strip() != '':
        parm.append(Case.case_name.contains(task_querys['job_name']))
    if task_querys['status'].strip() != '':
        parm.append(Case.case_name.contains(task_querys['status']))
    if task_querys['task_name'].strip() != '':
        parm.append(Case.case_name.contains(task_querys['task_name']))
    page_data = db.session.query(JobTask).filter(*parm).order_by(JobTask.create_time.desc()).paginate(page=task_querys['page_num'],
                                                                 per_page=task_querys['page_per'], error_out=False)
    response_task_dic = {}
    response_task_list = []
    if page_data.items:
        for msg in page_data.items:
            response_task_dic['id'] = msg.id
            response_task_dic['task_name'] = msg.task_name
            response_task_dic['status'] = msg.status
            response_task_dic['job_name'] = msg.job_name
            response_task_dic['ding_token'] = msg.ding_token
            response_task_dic['create_time'] = msg.create_time.strftime("%Y-%m-%d")
            response_task_list.append(response_task_dic.copy())
            response_task_dic.clear()
    response_task_dic['items'] = response_task_list
    response_task_dic['total'] = page_data.total
    return response_task_dic


def get_search_list(data):
    kw = data['search']
    kws = '%' + kw + '%'
    print(kws)
    data_list = db.session.query(JobTask).filter(JobTask.task_name.like(kws)).filter(
        JobTask.task_name.like(kws)).order_by(JobTask.create_time.desc()).paginate(page=data['page_num'],
                                              per_page=data['page_per'], error_out=False)
    response_task_dic = {}
    response_task_list = []

    if data_list.items:
        for msg in data_list.items:
            response_task_dic['id'] = msg.id
            response_task_dic['task_name'] = msg.task_name
            response_task_dic['status'] = msg.status
            response_task_dic['job_name'] = msg.job_name
            response_task_dic['ding_token'] = msg.ding_token
            response_task_dic['create_time'] = msg.create_time.strftime("%Y-%m-%d")
            response_task_list.append(response_task_dic.copy())
            response_task_dic.clear()
    response_task_dic['items'] = response_task_list
    response_task_dic['total'] = data_list.total
    return response_task_dic


# 添加项目
def add_task(taskname, jobname, dingtoken):
    now_time = datetime.datetime.now()
    insert = JobTask(task_name=taskname, job_name=jobname, status=0, ding_token=dingtoken, create_time=now_time)
    try:
        db.session.add(insert)
        db.session.commit()
        # db.session.close()
        return const.INSERT_SUCCESS
    except:
        db.session.rollback()
        return const.INSERT_FAIL


# 删除项目
def del_task(id):
    db.session.query(JobTask.status).filter(JobTask.id == id).update({'status': 3})
    try:
        db.session.commit()
        # db.session.close()
        return const.DELETE_SUCCESS
    except:
        db.session.rollback()
        return const.DELETE_FAIL


# 启动
def begin_task(id):
    db.session.query(JobTask.status).filter(JobTask.id == id).update({'status': 1})
    try:
        db.session.commit()
        # db.session.close()
        message = const.TASK_START_SUCCESS
    except:
        db.session.rollback()
        message = const.TASK_START_FAIL
    return message


# 停止
def stop_task(id):
    db.session.query(JobTask.status).filter(JobTask.id == id).update({'status': 0})
    try:
        db.session.commit()
        # db.session.close()
        message = const.TASK_STOP_SUCCESS
    except:
        db.session.rollback()
        message = const.TASK_STOP_FAIL
    return message


# 根据任务ID修改任务
def upjobtask_byid(id, taskname, jobname, dingtoken, status):
    a = db.session.query(JobTask.id, JobTask.task_name, JobTask.job_name, JobTask.ding_token).filter(
        JobTask.id == id).update(
        {'task_name': taskname, 'job_name': jobname, 'ding_token': dingtoken, 'status': status})
    try:
        db.session.commit()
        message = const.EDIT_SUCCESS
    except:
        db.session.rollback()
        message = const.EDIT_FAIL
    return message


def sel_case(group, project):
    """
    查询case,根据业务线、产品线获取case
    :param group: 业务线
    :param project: 产品线
    :return: 集合
    """
    result = db.session.query(Case.id, Case.case_name).filter(Case.group_name == group,
                                                              Case.project_name == project).all()
    db.session.commit()
    list = []
    for a in result:
        content = {
            'id': a[0],
            'case_name': a[1],
        }
        list.append(content)
    return list


# 添加case
def add_case(task_id, case_id, node_id):
    """
    添加case
    :param task_id: 任务id
    :param case_id: 用例id
    :return: string
    """
    insert = Taskcase(task_id=task_id, case_id=case_id, node_id=node_id, is_deploy=0)
    try:
        db.session.add(insert)
        db.session.commit()
        # db.session.close()
        message = const.INSERT_SUCCESS
    except:
        db.session.rollback()
        message = const.INSERT_FAIL

    return message


def sel_taskcase(taskid):
    """
    查询任务下的case
    :param taskid: 任务id
    :return: string
    """
    result = db.session.query(Case, Node, Taskcase).join(Case, Taskcase.case_id == Case.id).join(Node,
                                                                                                 Taskcase.node_id == Node.id).filter(
        Taskcase.task_id == taskid).all()
    list = []
    if result:
        for a in result:
            content = {
                'id': a.Case.id,
                'group_name': a.Case.group_name,
                'project_name': a.Case.project_name,
                'case_name': a.Case.case_name,
                'node_name': a.Node.node_name,
                'is_deploy': a.Taskcase.is_deploy,
                'case_type': a.Case.case_type,
                'node_id': a.Taskcase.node_id,
                'task_id': a.Taskcase.task_id,
            }
            list.append(content)
    return list


def add_case_deploy(case_id, node_id, task_id):
    """
    添加case之后自动部署
    :param case_id: 用例id
    :param node_id: 节点id
    :param task_id: 任务id
    :return: string
    """
    case = db.session.query(Case).filter(Case.id == case_id).first()
    if case.case_type == 3:  # 接口自动化不需要部署
        msg = const.OPERATE_SUCCESS
    else:
        is_deploy_list = db.session.query(Taskcase.is_deploy).filter(Taskcase.case_id == case_id).all()
        if is_deploy_list:  # 查询Taskcase中间表时候已经存在此用例id得数据
            if all(is_deploy[0] == 0 for is_deploy in is_deploy_list):  # 列表中得用例是否都已经部署，都是未部署得状态就进行部署
                msg = case_library_service.call_method(case_id=case_id, sign="deployee", node_id=node_id, task_id=task_id)
            else:
                msg = const.OPERATE_SUCCESS  # 有且存在此用例id的数据已经部署，直接返回成功，不再进行重复部署
        else:
            msg = case_library_service.call_method(case_id=case_id, sign="deployee", node_id=node_id, task_id=task_id)

    return msg


def del_case(taskid, caseid):
    """
    删除case
    :param taskid: 任务id
    :param caseid: 用例id
    :return: message
    """

    try:
        totol = db.session.query(Taskcase).filter(Taskcase.task_id == taskid, Taskcase.case_id == caseid).delete()
        if totol == 1:
            message = const.DELETE_SUCCESS
        else:
            message = const.DELETE_FAIL_CASE_NON_EXISTENT
        db.session.commit()
        db.session.close()
    except:
        db.session.rollback()
        message = const.DELETE_FAIL
    return message
